/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: decoded_mbuf_yuv_sender head file
 */
#ifndef DECODED_MBUF_VIDEO_SENDER_H
#define DECODED_MBUF_VIDEO_SENDER_H

#include <cstdint>
#include <getopt.h>
#include <pthread.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/time.h>
#include <sys/prctl.h>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include "acl.h"
#include "acl_rt.h"
#include "hi_dvpp.h"

#include "image_sender_base.h"
#include "mdc/cam/camera/cameradecodedmbufserviceinterface_skeleton.h"
#include "util.h"
#include "core/types.h"
#include "driver/ascend_hal.h"
#include "securec.h"

#include "driver/ascend_hal.h"
#include "driver/ascend_hal_define.h"

const int32_t MAX_NAME_LENGTH = 500;

struct GetFrameMsg {
    uint32_t chanId = 0;
    uint8_t *inputFileBuf = nullptr;
    uint32_t *frameCount = nullptr;
    uint32_t fileSize = 0;
    hi_payload_type type = HI_PT_H264;
    uint8_t *dataDev = nullptr;

    void *outBuffer = nullptr;
    uint32_t outBufferSize = 0;
    uint32_t outFormat = 0;
    hi_vdec_stream stream;
    uint32_t readCount = 0;
};

struct InputMsg {
    FILE *fpInputFile = NULL;
    aclError aclRet = ACL_SUCCESS;
    uint32_t fileSize = 0;
    uint8_t *inputFileBuf = NULL;
    uint32_t readLen = 0;
    int32_t ret = HI_SUCCESS;
};

struct DealDecRunNode {
    uint32_t imageSize;
    uint32_t chanId;
    uint32_t outWidthStride;
    uint32_t outHeightStride;
};

using MbufSkeleton = mdc::cam::camera::skeleton::CameraDecodedMbufServiceInterfaceSkeleton;

class DecodedMbufVideoSender : public ImageSenderBase<MbufSkeleton> {
    using PFunc = void *(*)(void *);

public:
    aclrtContext g_context = NULL;

public:
    DecodedMbufVideoSender() = default;
    DecodedMbufVideoSender(uint32_t id, cv::Size s, std::string dir) : ImageSenderBase<MbufSkeleton>(id, s, dir)
    {
        g_in_width = s.width;
        g_in_height = s.height;
        g_out_width = s.width;
        g_out_height = s.height;
        if (g_comPara.fileType == "h264") {
            g_in_format = 0;
        } else if (g_comPara.fileType == "h265") {
            g_in_format = 1;
        }
        g_out_format = 0;
        g_is_write_file = 1;
        g_out_width_stride = s.width;
        g_out_height_stride = s.height;
        sourceYuvPath = dir;
        if (dir.back() != '/') {
            sourceYuvPath += std::string("/") + "videoSource.yuv";
        } else {
            sourceYuvPath += "videoSource.yuv";
        }
#ifdef SAVE_SENDER_FILE
        fp_yuv = fopen(sourceYuvPath.c_str(), "wb+");
#endif
        sec = std::chrono::high_resolution_clock::now();
    }
    ~DecodedMbufVideoSender()
    {
        if (dataSkeleton != nullptr) {
            dataSkeleton->StopOfferService();
            dataSkeleton = nullptr;
        }
        if (handle != nullptr) {
            halBuffDeletePool(handle);
        }
    };

    bool RegisterSender()
    {
        std::cout << "Begin register MBUF image sender." << std::endl;
        auto result = ImageSenderBase<MbufSkeleton>::RegisterSender();
        std::cout << "Finished to register MBUF image sender." << std::endl;
        return result;
    }

    bool VdecDecoded()
    {
        std::string path = dir;
        std::string postfix = g_comPara.fileType;
        bool isLoop = g_comPara.loop;
        std::vector<std::string> files;
        int32_t fileCnt = getFilesBySort(path, files, g_comPara.fileType);
        if (fileCnt == 0) {
            std::cout << "PATH:" << path << " has no files!" << std::endl;
            return false;
        }
        do {
            for (auto &file : files) {
                if (file.empty()) {
                    std::cerr << "File not exist, or corrupt.path: " << file << std::endl;
                    return false;
                }
                errno_t ret = memset_s(g_input_file_name, sizeof(g_input_file_name), 0, MAX_NAME_LENGTH);
                if (ret != EOK) {
                    std::cout << "memset_s failed:" << ret << std::endl;
                    return false;
                }
                if (strcpy_s(g_input_file_name, file.length() + 1, file.c_str()) != 0) {
                    std::cout << "strcpy_s g_input_file_name failed, file_name:" << g_input_file_name << std::endl;
                    return false;
                }
                VdecInit();
                InitThreadPara();
                VdecProcess();
                VdecUninit();
            }
        } while (isLoop);
#ifdef SAVE_SENDER_FILE
        if (fclose(fp_yuv) != 0) {
            std::cout << " fclose(fp_yuv) != 0 " << std::endl;
        }
#endif
        return true;
    }

    void InitThreadPara()
    {
        g_send_exit_state[VDEC_MAX_CHN_NUM] = {0};
        g_get_exit_state[VDEC_MAX_CHN_NUM] = {0};
        g_vdec_send_thread[VDEC_MAX_CHN_NUM] = {};
        g_vdec_get_thread[VDEC_MAX_CHN_NUM] = {};
        g_send_thread_id[VDEC_MAX_CHN_NUM] = {0};
        g_get_thread_id[VDEC_MAX_CHN_NUM] = {0};
    }
    int32_t VdecInit()
    {
        PrintParameter();
        int32_t ret = HI_SUCCESS;
        ret = hi_dvpp_init();
        if (ret != HI_SUCCESS) {
            printf("[%s][%d] hi_dvpp_init failed !\n", __FUNCTION__, __LINE__);
            return -1;
        }
        ret = vdec_create();
        if (ret != HI_SUCCESS) {
            printf("[%s][%d] VdecStart failed \n", __FUNCTION__, __LINE__);
            VdecDestroy();
            HiDvppDeinit();
            return -1;
        }
        InitOutbufferLock();
        GetStartTime();
        return ret;
    }
    void VdecUninit()
    {
        WaitVdecEnd();
        ShowDecodePerformance();
        DestroyOutbufferLock();
        VdecDestroy();
        HiDvppDeinit();
    }
    int32_t VdecProcess()
    {
        int32_t ret = HI_SUCCESS;
        ret = create_send_stream_thread();
        if (ret != 0) {
            StopSendStreamThread();
        } else {
            ret = create_get_pic_thread();
            if (ret != 0) {
                StopGetPicThread();
            }
        }
        return ret;
    }
    int32_t BufCreatePool(const uint32_t blkSize, const uint32_t blkNum)
    {
        constexpr uint32_t alignSize = 32U;
        mpAttr attr;
        attr.devid = 0;
        attr.mGroupId = 0;
        attr.blkSize = ((blkSize + alignSize) - 1U) & (~(alignSize - 1));
        attr.blkNum = blkNum;
        attr.align = alignSize;
        attr.hugePageFlag = 1U;
        const int32_t ret = halBuffCreatePool(&attr, &handle);
        if (ret != DRV_ERROR_NONE) {
            std::cout << "halBuffCreatePool error: " << ret << std::endl;
            return -1;
        }
        return 0;
    }
    int32_t CopyToMbuf(uintptr_t &mbuf, const uint8_t *src, const uint32_t len) const
    {
        Mbuf *pMbuf = nullptr;
        int32_t ret = halMbufAllocByPool(handle, &pMbuf);
        if (ret != DRV_ERROR_NONE) {
            std::cout << "halMbufAllocByPool error: " << ret << std::endl;
            return -1;
        }
        if (pMbuf == nullptr) {
            std::cout << "halMbufAllocByPool mbuf null" << std::endl;
            return -1;
        }
        void *dst = nullptr;
        uint64_t bufSize = 0U;
        ret = halMbufGetDataPtr(pMbuf, &dst, &bufSize);
        if (ret != 0 || dst == nullptr) {
            std::cout << "MbufGetDataPtr error: " << ret << std::endl;
            halBuffFree(pMbuf);
            return -1;
        }
        if (len > bufSize) {
            std::cout << "Error: Src data length[" << len << "] > mbuf size[" << bufSize << "]" << std::endl;
            halBuffFree(pMbuf);
            return -1;
        }
        if (memcpy_s(reinterpret_cast<uint8_t *>(dst), static_cast<uint64_t>(bufSize), src,
            static_cast<uint64_t>(len)) != 0) {
            std::cout << "Error: Copy src data to mbuf error!" << std::endl;
            halBuffFree(pMbuf);
            return -1;
        }
        ret = halMbufSetDataLen(pMbuf, len);
        if (ret != DRV_ERROR_NONE) {
            std::cout << "halMbufSetDataLen error: " << ret << std::endl;
            halBuffFree(pMbuf);
            return -1;
        }
        mbuf = reinterpret_cast<uintptr_t>(pMbuf);
        return 0;
    }
    void FillImageAndSend(std::string imgPath, uint32_t seq, int32_t *gStopFlag) override {}

public:
    int32_t get_option(int32_t argc, char **argv);
    void option_switch_al(int32_t parameter);
    void option_switch_mv(int32_t parameter);
    int32_t check_option();
    void CheckOptionFormat();
    void PrintParameter();
    void vdec_handle_signal(int32_t signo);
    int32_t vdec_create();
    void VdecDestroy();
    int32_t create_send_stream_thread();
    int32_t create_get_pic_thread();
    void StopSendStreamThread();
    void StopGetPicThread();
    static void *SendStream(DecodedMbufVideoSender *thiz);
    static void *GetPic(DecodedMbufVideoSender *thiz);
    void GetEveryFrame(GetFrameMsg& frameMsg);
    void delay_exec(uint64_t execTime, int32_t seconds);
    void WaitVdecEnd();
    void ShowDecodePerformance();
    void GetStartTime();
    void InitOutbufferLock();
    void DestroyOutbufferLock();
    void release_outbuffer(uint32_t chanId);
    int32_t hi_dvpp_init();
    int32_t HiDvppDeinit();

private:
    poolHandle handle;
    float lastTime = 0.0F;
    const int32_t frameWidthTriploid = 3;

    const int32_t sleepTimeIntervalMs { 1000000 };

    char g_input_file_name[MAX_NAME_LENGTH] = "test264.h264";
    char g_output_file_name[MAX_NAME_LENGTH] = "./outfile";
    uint32_t g_in_width = 3840;  // input stream width
    uint32_t g_in_height = 2160; // input stream height
    uint32_t g_in_format = 0;
    uint32_t g_in_bitwidth = 8;
    uint32_t g_out_width = 0;
    uint32_t g_out_height = 0;
    uint32_t g_out_format = 0;
    uint32_t g_out_width_stride = 4096;
    uint32_t g_out_height_stride = 4096;
    uint32_t g_is_write_file = 1;
    uint32_t g_chn_num = 1;
    uint32_t g_ref_frame_num = 8;
    uint32_t g_display_frame_num = 2;
    uint32_t g_output_order = 0;
    uint32_t g_send_times = 1;
    uint32_t g_send_interval = 0;
    uint32_t g_delay_time = 1;
    uint32_t g_alloc_num = 20;
    uint32_t g_start_chn_num = 0;
    uint32_t g_render = 0;
    uint32_t g_exit = 0;

    uint32_t g_chan_create_state[VDEC_MAX_CHN_NUM] = {0};
    uint64_t g_start_time = 0;

    std::vector<void *> g_out_buffer_pool[VDEC_MAX_CHN_NUM];
    pthread_mutex_t g_out_buffer_pool_lock[VDEC_MAX_CHN_NUM];

    uint32_t g_send_exit_state[VDEC_MAX_CHN_NUM] = {0};
    uint32_t g_get_exit_state[VDEC_MAX_CHN_NUM] = {0};

    std::thread g_vdec_send_thread[VDEC_MAX_CHN_NUM] = {};
    std::thread g_vdec_get_thread[VDEC_MAX_CHN_NUM] = {};
    uint32_t g_send_thread_id[VDEC_MAX_CHN_NUM] = {0};
    uint32_t g_get_thread_id[VDEC_MAX_CHN_NUM] = {0};

    uint8_t *g_frame_addr[VDEC_MAX_CHN_NUM][9999];
    uint64_t g_frame_len[VDEC_MAX_CHN_NUM][9999];
    uint64_t g_vdec_start_time[VDEC_MAX_CHN_NUM] = {0};
    uint64_t g_vdec_end_time[VDEC_MAX_CHN_NUM] = {0};
    uint64_t g_vdec_get_frame_cnt[VDEC_MAX_CHN_NUM] = {0};

    aclrtRunMode g_run_mode = ACL_HOST;
    std::string sourceYuvPath;
    FILE *fp_yuv;
    std::chrono::high_resolution_clock::time_point sec;
    DealDecRunNode dealDecRunNode;

private:
    int32_t InitGrp(void);
    void get_current_time_us(uint64_t &timeUs);
    bool save_yuv_file(FILE *const fd, hi_video_frame frame, uint32_t chanId);
    void SaveRgbFileAclHost(hi_video_frame frame, uint8_t *outImageBuf, FILE * const fd, uint32_t chanId);
    void SaveYuvFileAclHost(hi_video_frame frame, uint8_t *outImageBuf, FILE * const fd, uint32_t chanId);
    bool DealRunNode(uint8_t *addr, hi_video_frame frame, FILE * const fd);
    static void GetPicHost(hi_video_frame_info& frame, DecodedMbufVideoSender *thiz,
        uint32_t& chanId, hi_vdec_stream& stream, int32_t& writeFileCnt);
    static void UpdateOutPicInfo(hi_vdec_pic_info &outPicInfo, DecodedMbufVideoSender *thiz, uint32_t chanId,
        GetFrameMsg& frameMsg);
    static int32_t DealSendFormat(DecodedMbufVideoSender *thiz, GetFrameMsg& frameMsg, FILE *fpInputFile);
    static bool DealDataDev(DecodedMbufVideoSender *thiz,  uint8_t *dataDev, FILE *fpInputFile,
        GetFrameMsg& frameMsg);
    static void DealInput(DecodedMbufVideoSender *thiz, InputMsg& inputMsg);
    void GetFrameHost(int32_t& i, int32_t& readLen, uint8_t *bufPointer, bool& isFindStart, bool& isFindEnd);
    void DealGetFrameHost(int32_t& i, int32_t& readLen, uint8_t *bufPointer, bool& isFindStart, bool& isFindEnd);
    bool FillYuvAndSend(uint8_t *ptr, int32_t w, int32_t h);
    bool save_rgb_file(FILE *const fd, hi_video_frame frame, uint32_t chanId);
    bool vdec_reset_chn(uint32_t chanId);
    int32_t DealParam(uint32_t index);
    static void DealDecResult(int32_t& decResult, int32_t& successCnt, uint32_t& chanId, int32_t& failCnt);
};

#endif // DECODED_MBUF_VIDEO_SENDER_H
